package mongo

import (
	"context"
	"log"
	"oc_saas/glo"
	"os"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

// 初始化mongo
func InitMongo() *mongo.Client {
	client := options.Client().ApplyURI("mongodb://" + glo.OC_CONF.Mongo.User + ":" + glo.OC_CONF.Mongo.Password + "@" + glo.OC_CONF.Mongo.Addr + ":" + glo.OC_CONF.Mongo.Port + "/?authSource=admin")
	mongoClient, err := mongo.Connect(context.TODO(), client)
	if err != nil {
		log.Fatal(err)
		os.Exit(0)
	}
	err = mongoClient.Ping(context.TODO(), nil)
	if err != nil {
		log.Fatal(err)
		os.Exit(0)
	}
	return mongoClient
}

type MongoLink struct {
	Addr        string
	Port        string
	User        string
	Password    string
	ClusterName string
}

// mongo集群
func InitMongoCluster(mongoClusterList []*MongoLink) []*mongo.Client {
	var list []*mongo.Client
	for _, v := range mongoClusterList {
		client := options.Client().ApplyURI("mongodb://" + v.User + ":" + v.Password + "@" + v.Addr + ":" + v.Port + "/?authSource=admin")
		mongoClient, err := mongo.Connect(context.TODO(), client)
		if err == nil {
			list = append(list, mongoClient)
		}
	}
	return list
}
